// pages/login/forgetPassword/index.js
import { useErrMessage, useInfoMessage } from '@/utils/message'
import { apiSendEmailVerificationCode, apiForgotPassword} from '@/api/user'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    labelEmail: '邮\u00A0\u00A0\u00A0箱', //给t-input的label属性，对齐文本而已，直接写无法转义
    navBarHeight: 0,  // 导航栏总高度
    countdown: 0, // 倒计时秒数
    timer: null,    // 定时器
    isEmail: false, // 检测是不是email
    isSubmit: false,  //是否能提交
    passwordVisible: false, //密码是否可见

    email: '',
    password: '',
    code: '',
  },
  
  async retrieve() {
    let msg = ''
    let isOk = false
    let data = ''
    const { email, password, code } = this.data
    data = await apiForgotPassword({ email, password, code })
    if (data.code === 200) {
      msg = "修改成功"
      isOk = true
    } else {
      msg = data.msg
    }
    if (isOk) {
      useInfoMessage(this, msg)
      // 延迟2秒（与Message的duration一致）后跳转
      setTimeout(() => {
        wx.navigateBack()
      }, 2000);
    } else {
      useErrMessage(this, msg)
    }
  },

  // 发送验证码函数
  handleSendVerifyCode() {
    if (this.data.countdown > 0) return;
    
    apiSendEmailVerificationCode(this.data.email)
      .then((res) => {
        if (res.code===200){
          useInfoMessage(this, "发送成功");
          this.startCountdown(60); // 60秒倒计时
        }else{
          useErrMessage(this,res.msg)
        }
      })
      .catch(err => {
        console.error("发送验证码失败:", err);
      });
  },

  startCountdown(seconds) {
    if (this.data.timer) clearInterval(this.data.timer);
    
    this.setData({ countdown: seconds });
    
    const timer = setInterval(() => {
      this.setData({
        countdown: this.data.countdown - 1
      }, () => {
        if (this.data.countdown <= 0) {
          clearInterval(timer);
          this.setData({ timer: null });
        }
      });
    }, 1000);
    
    this.setData({ timer });
  },

  onUnload() {
    if (this.data.timer) clearInterval(this.data.timer);
  },

  // 是否运行提交
  changeSubmit() {
    const { isEmail, email, password, code } = this.data
    if (isEmail && email !== '' && password !== '' && code !== '') {
      this.setData({ isSubmit: true });
    } else {
      this.setData({ isSubmit: false });
    }
  },

  // 密码可见与不可见
  togglePasswordVisibility() {
    this.setData({
      passwordVisible: !this.data.passwordVisible,
    });
  },
  onEmailClear(){
    this.onEmailInput({ detail: { value: '' } });
  },
  onPasswordClear(){
    this.onPasswordInput({ detail: { value: '' } });
  },
  onCodeClear(){
    this.onCodeInput({ detail: { value: '' } });
  },
  onEmailInput(e) {
    // 邮箱正则表达式（支持大多数常见格式）
    // const isEmail = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(e.detail.value);
    const isEmail = true

    this.setData({
      isEmail,
      email: e.detail.value,
    });
    this.changeSubmit();
  },
  onPasswordInput(e) {
    this.setData({
      password: e.detail.value,  // 更新数据
    });
    this.changeSubmit();
  },
  onCodeInput(e) {
    this.setData({
      code: e.detail.value
    });
    this.changeSubmit();
  },

  calculateNavBarHeight() {
    // 获取胶囊按钮信息
    const menuInfo = wx.getMenuButtonBoundingClientRect();
    // 计算导航栏总高度（胶囊高度 + 上下安全距离）
    const navBarHeight = menuInfo.height + (menuInfo.top) * 1.5;

    this.setData({ navBarHeight });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.calculateNavBarHeight();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})